﻿using System;
using System.Linq;
using System.Web.Http;
using ELearning.BLL;
using ELearning.Common.CommonStr;
using ELearning.Common.Extensions;
using ELearning.Common.Helpers;
using ELearning.Common.Model;
using ELearning.Models;
using ELearning.Models.ViewModel.YTJYAdmin.VideoLib;

namespace ELearning.API.Controllers.YTJYAdminController
{
    /// <summary>
    /// 视频库操作控制器
    /// </summary>
    public class VideoLibController : BaseApiController
    {
        /// <summary>
        /// 视频库相关操作server
        /// </summary>
        private EVideoLibService eVideoLibService => new EVideoLibService();

        /// <summary>
        /// 腾讯云视频操作日志
        /// </summary>
        private TTencentLogService tencentLogService => new TTencentLogService();

        /// <summary>
        /// 获取视频库列表
        /// </summary>
        [HttpPost, Route("api/ytjyadmin/VideoLib/GetModelList")]
        public ServiceResponse<VideoLibViewModel> GetModelList(VideoLibRequest request)
        {
            var viewModel = eVideoLibService.GetVideoLibList(request, CurrentUserModel.OrgCode);

            return ServiceResponse<VideoLibViewModel>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }

        /// <summary>
        /// 新增或者更新视频信息
        /// </summary>
        [HttpPost, Route("api/ytjyadmin/VideoLib/AddModel")]
        public ServiceResponse<bool> AddModel(VideoLibAddModel viewModel)
        {
            if (viewModel.IsNotNull() && viewModel.Items.IsNotNull() && viewModel.Items.Any())
            {
                var sort = eVideoLibService.FindList(x => !x.IsDelete).OrderByDescending(x => x.Sort).ThenBy(x => x.CreateTime).FirstOrDefault()?.Sort ?? 0;

                foreach (var video in viewModel.Items)
                {
                    var model = new EVideoLib
                    {
                        UpdateTime = DateTime.Now,
                        UpdateUserId = CurrentUserModel.UserId,
                        CreateTime = DateTime.Now,
                        CreateUserId = CurrentUserModel.UserId,
                        Id = Guid.NewGuid(),
                        OrgCode = CurrentUserModel.OrgCode ?? string.Empty,
                        CategoryId = viewModel.CategoryId,
                        TypeCode = viewModel.TypeCode,
                        CoverUrl = string.Empty,
                        ConvertVideoNote = string.Empty,
                        IsDelete = false,
                        Sort = ++sort,
                        Name = video.Name,
                        Status = 1,
                        FileId = video.FileId,
                        Description = video.Name,
                        DownloadUrl = video.DownloadUrl,
                        Size = video.Size,
                        Duration = 0,
                        PlayUrl0 = string.Empty,
                        PlayUrl1 = string.Empty,
                        PlayUrl2 = string.Empty,
                        PlayUrl3 = string.Empty
                    };

                    if (!string.IsNullOrEmpty(model.FileId) && !string.IsNullOrEmpty(model.DownloadUrl))
                    {
                        model.Status = 2;
                        var res = TencentCloudHelper.StartConvertVideo(model.FileId);
                        model.ConvertVideoNote = res;
                    }

                    eVideoLibService.AddNoSaveChange(model);
                }

                eVideoLibService.SaveChange();
            }

            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 新增或者更新视频信息
        /// </summary>
        [HttpPost, Route("api/ytjyadmin/VideoLib/PostModel")]
        public ServiceResponse<bool> PostModel(VideoLibPostModel viewModel)
        {
            var model = eVideoLibService.Find(v => v.Id == viewModel.Id);
            if (model.IsNotNull())
            {
                if (!string.IsNullOrEmpty(viewModel.DownloadUrl))
                {
                    if (!viewModel.DownloadUrl.Equals(model.DownloadUrl))
                    {
                        var res = TencentCloudHelper.StartConvertVideo(viewModel.FileId);
                        model.ConvertVideoNote = res;
                        model.Status = 2;
                        model.Duration = 0;
                    }
                }
                else
                {
                    model.Status = 0;
                }
                model.UpdateTime = DateTime.Now;
                model.UpdateUserId = CurrentUserModel?.UserId ?? Guid.Empty;
                model.Name = viewModel.Name;
                model.Description = viewModel.Description;
                model.FileId = viewModel.FileId;
                model.Size = viewModel.Size;
                model.CoverUrl = viewModel.CoverUrl;
                model.CategoryId = viewModel.CategoryId;
                model.TypeCode = viewModel.TypeCode;
                model.Sort = viewModel.Sort;
                model.DownloadUrl = viewModel.DownloadUrl;

                eVideoLibService.Update(model);
            }
            else
            {
                model = viewModel.MapTo<EVideoLib, VideoLibPostModel>();
                model.UpdateTime = DateTime.Now;
                model.UpdateUserId = CurrentUserModel?.UserId ?? Guid.Empty;

                model.CreateTime = DateTime.Now;
                model.CreateUserId = CurrentUserModel?.UserId ?? Guid.Empty;
                model.Id = Guid.NewGuid();
                model.OrgCode = CurrentUserModel?.OrgCode ?? string.Empty;

                if (!string.IsNullOrEmpty(model.FileId) && !string.IsNullOrEmpty(model.DownloadUrl))
                {
                    model.Status = 2;
                    var res = TencentCloudHelper.StartConvertVideo(model.FileId);
                    model.ConvertVideoNote = res;
                }

                eVideoLibService.Add(model);
            }
            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 删除视频
        /// </summary>
        [HttpGet, Route("api/ytjyadmin/VideoLib/DeleteModel")]
        public ServiceResponse<bool> DeleteModel(Guid videoId)
        {
            var model = eVideoLibService.Find(v => v.Id == videoId);

            if (model.IsNotNull())
            {
                model.IsDelete = true;
                model.UpdateTime = DateTime.Now;
                model.UpdateUserId = CurrentUserModel?.UserId ?? Guid.Empty;
                eVideoLibService.Update(model);
            }

            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 腾讯云视频转码回调
        /// </summary>
        [HttpPost, Route("api/ytjyadmin/VideoLib/TencentCallback")]
        [AllowAnonymous]
        public ServiceResponse<bool> TencentCallback(ReqCallback req)
        {
            //转码文档，https://cloud.tencent.com/document/product/266/33478
            //转码回调文档，https://cloud.tencent.com/document/product/266/34071
            WriteHelper.WriteFile("api/ytjyadmin/VideoLib/TencentCallback------req--------------------------" + DateTime.Now);
            WriteHelper.WriteFile(req);
            if (req.IsNull())
                req = new ReqCallback();
            try
            {
                tencentLogService.Add(new TTencentLog
                {
                    Id = Guid.NewGuid(),
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    CreateUserId = Guid.Empty,
                    UpdateUserId = Guid.Empty,
                    IsDelete = false,
                    CallBackLog = req.ToJson(),
                    FileId = req.ProcedureStateChangeEvent?.FileId
                });
            }
            catch (Exception e)
            {
                WriteHelper.WriteFile(e.Message);
            }

            if (string.IsNullOrEmpty(req.EventType))
                req.EventType = string.Empty;

            //确定是否为任务流变更事件
            if (req.EventType.Equals(TencentCallBackType.ProcedureStateChanged) && req.ProcedureStateChangeEvent?.ErrCode == 0)
            {
                var video = eVideoLibService.Find(v => v.FileId == req.ProcedureStateChangeEvent.FileId);
                if (video.IsNotNull())
                {
                    foreach (var resultSet in req.ProcedureStateChangeEvent.MediaProcessResultSet)
                    {
                        //type为转码进行下一步
                        if (resultSet.Type.Equals("Transcode", StringComparison.CurrentCultureIgnoreCase))
                        {
                            var output = resultSet.TranscodeTask.Output;
                            video.Duration = (int)output.Duration;
                            video.PlayUrl0 = output.Url;
                            video.PlayUrl1 = output.Url;
                            video.PlayUrl2 = output.Url;
                            video.PlayUrl3 = output.Url;
                            video.Status = 3;
                            eVideoLibService.Update(video);

                            WriteHelper.WriteFile($"video--------------{video.ToJson()}");
                        }
                    }
                }
            }

            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, true);
        }

        /// <summary>
        /// 获取视频库全部列表
        /// </summary>
        [HttpGet, Route("api/ytjyadmin/VideoLib/GetAllVideoList")]
        public ServiceResponse<object> GetAllVideoList()
        {
            var models = eVideoLibService.FindList(e => !e.IsDelete && e.OrgCode == CurrentUserModel.OrgCode).Select(e => new { value = e.Id, label = e.Name }).ToList();

            return ServiceResponse<object>.SuccessResponse(CommonConst.OprateSuccessStr, models);
        }

    }
}